package com.shop.auth.config;

import com.shop.auth.utils.RsaUtils;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;

import javax.annotation.PostConstruct;
import java.io.File;
import java.security.PrivateKey;
import java.security.PublicKey;

/**
 * @author : Created by HGL on 2019/03/29 14:02
 * @version : 1.0
 * Description :
 */
@ConfigurationProperties(prefix = "sp.jwt")
@Data
public class JwtProperties {
    private String secret; // 密钥

    private String pubKeyPath;// 公钥文件路径

    private String priKeyPath;// 私钥文件路径

    private int expire;// token过期时间

    private String cookieName;//cookie名称

    private int cookieMaxAge;//cookie的过期时间

    private PublicKey publicKey; // 公钥

    private PrivateKey privateKey; // 私钥

    private static final Logger logger = LoggerFactory.getLogger(JwtProperties.class);

    @PostConstruct
    public void init(){
        try {
            File pubKey = new File(pubKeyPath);
            File priKey = new File(priKeyPath);
            //公钥和私钥如果不存在
            if (!pubKey.exists() || !priKey.exists()) {
                // 生成公钥和私钥
                RsaUtils.generateKey(pubKeyPath, priKeyPath, secret);
            }
            // 获取公钥和私钥
            this.publicKey = RsaUtils.getPublicKey(pubKeyPath);
            this.privateKey = RsaUtils.getPrivateKey(priKeyPath);
        } catch (Exception e) {
            logger.error("初始化公钥和私钥失败！", e);
            throw new RuntimeException();
        }
    }
}
